import os
import sys

from PyPDF2 import PdfFileMerger
# from pdfplumber import PdfFileMerger
from PySide6.QtWidgets import *


class PDFGuiFrame(QFrame):

    def __init__(self, folderPath='./'):
        self.folder_path = folderPath
        super().__init__()
        self.setWindowTitle('PDF合并')
        self.resize(400, 100)
        self.show()

        # 创建一个面板

        panel = QWidget(parent=self)
        # 面板中添加一个文本控件
        self.txt = QLabel(parent=panel, label="默认路径：" + self.folder_path)
        self.btn = QPushButton(parent=panel, label='选择', id=5, pos=(150, 20))
        self.Bind(QPushButton, self.btn_click, None, id=5)

    def btn_click(self, event):
        id = event.GetId()
        if id == 5:
            btn_lab = self.btn.GetLabelText()
            if btn_lab == '选择':
                dlg = QDialog(self, r"选择文件夹", style=DD_DEFAULT_STYLE)
                if dlg.ShowModal() == 'OK':
                    self.folder_path = dlg.GetPath()  # 文件夹路径
                dlg.Destroy()
                self.txt.SetLabelText("选择路径：" + self.folder_path)
                self.btn.SetLabelText('合并')
            else:
                self.txt.SetLabelText('合并开始...')
                self.pdf_merge()
                self.txt.SetLabelText(
                    '合并完成：' + os.path.join(self.folder_path, 'pdf_merge.pdf'))
                self.btn.SetLabelText('选择')

    def pdf_file_list(self):
        """
        获取文件夹中所有的.pdf类型的文件路径,包含子文件夹
        :return:
        """
        # 判断文件夹路径是否存在
        assert os.path.exists(
            self.folder_path), 'The folder path does not exist'
        pdf_paths = list()
        for root, dirs, files in os.walk(self.folder_path):
            for file in files:
                if file.endswith('.pdf'):
                    pdf_paths.append(os.path.join(root, file))
        return pdf_paths

    def pdf_merge(self, merge_name='pdf_merge.pdf'):
        """
        :param merge_name: 合并后的文件名
        :return:
        """
        print('PDF合并开始...')
        pdf_lst = self.pdf_file_list()
        file_merger = PdfFileMerger()
        for pdf in pdf_lst:
            # 合并pdf文件
            file_merger.append(pdf)

        # 合并后的文件导出
        file_merger.write(os.path.join(self.folder_path, merge_name))
        print('PDF合并完成')


if __name__ == '__main__':
# if __name__ == '__pdfMerger__':
    app = QApplication(sys.argv)
    window = PDFGuiFrame()
    window.show()
    sys.exit(app.exec_())
